package com.monitor.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.monitor.dao.ErpCustomerCarMapper;
import com.monitor.dao.ErpCustomerLimitMapper;
import com.monitor.dao.ErpCustomerMapper;
import com.monitor.dao.ErpCustomerWarehouseMapper;
import com.monitor.dao.ErpInspectionContentMapper;
import com.monitor.dao.ErpMaterielMapper;
import com.monitor.dao.ErpSaleRepairRepairMapper;
import com.monitor.dao.ErpSaleRepairSaleMapper;
import com.monitor.dao.ErpTireArchivesWorkMapper;
import com.monitor.entity.ErpCustomer;
import com.monitor.entity.ErpCustomerCar;
import com.monitor.entity.ErpCustomerLimit;
import com.monitor.entity.ErpCustomerWarehouse;
import com.monitor.entity.ErpInspectionContent;
import com.monitor.entity.ErpInspectionOrder;
import com.monitor.entity.ErpMateriel;
import com.monitor.entity.ErpSaleRepairSale;
import com.monitor.entity.ErpTireArchivesWork;
import com.monitor.entity.Weelly;
import com.monitor.service.ErpSaleRepairSaleService;
import com.monitor.util.DataUtil;
import com.monitor.util.Result;
import com.monitor.util.TestPost;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 销售维修-销售表 服务实现类
 * </p>
 *
 * @author LX
 * @since 2018-09-12
 */
@Service
@Transactional
public class ErpSaleRepairSaleServiceImpl extends ServiceImpl<ErpSaleRepairSaleMapper, ErpSaleRepairSale> implements ErpSaleRepairSaleService {

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	static SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月");
	
	@Resource
	private ErpMaterielMapper erpMaterielMapper;
	
	@Resource
	private ErpCustomerCarMapper erpCustomerCarMapper;
	
	@Resource
	private ErpCustomerWarehouseMapper erpCustomerWarehouseMapper;
	
	@Resource
	private ErpTireArchivesWorkMapper erpTireArchivesWorkMapper;
	
	@Resource
	private ErpCustomerMapper erpCustomerMapper;
	
	@Resource
	private ErpCustomerLimitMapper erpCustomerLimitMapper;
	
	@Resource
	private ErpInspectionContentMapper erpInspectionContentMapper;
	
	@Resource
	private ErpSaleRepairSaleMapper erpSaleRepairSaleMapper;
	
	@Resource
	private ErpSaleRepairRepairMapper erpSaleRepairRepairMapper;
	
	@Override
	public  Result<List<Weelly>> findWeekly(Integer custId,String name, String workDtS, String workDtE) {
		// TODO Auto-generated method stub
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(DataUtil.strToDate(workDtS));
        
        calendar.add(Calendar.MONTH, -3);    //加一个月
		
		List<Weelly> wlList = new ArrayList<Weelly>(); //返回值
		//统计
		Weelly w = new Weelly();
		w.setCusName("单位");//单位
		w.setMileageWarning(0);//里程预警
		w.setTreadWarning(0);//胎纹预警
		w.setMileageLimitWarning(0);//里程达限预警
		w.setTreadLimiWarning(0);//胎纹达限预警
		w.setThisWeel(0);//本周更新w.setThisWeel(0);//本周更新
		w.setThisMonth(0);//本月更新
		w.setThisMonthPlan(0);//本月更新计划
		w.setAccident(0);//意外损耗
		w.setThisMonth(0);//本月更新
		w.setUpdateCompleted(0);//更新完成
		w.setRecentUpdatePlan(0);//近期更新计划
		wlList.add(w);
		
		//客户编码
		List<Integer> cusCodes = new ArrayList<Integer>();
		cusCodes.add(11111111);
		//客户ID
		List<Integer> cusIdL = new ArrayList<Integer>();
		cusIdL.add(-1);
		//客户名称
		List<String> cusNames = new ArrayList<String>();
		cusNames.add("单位");
		
		long startTIme = new Date().getTime();
		Map<String,Object> map = this.findCustomer(custId, cusCodes, cusIdL, cusNames, wlList);
		wlList = (List<Weelly>) map.get("wlList");
		cusCodes = (List<Integer>) map.get("cusCodes");
		cusIdL = (List<Integer>) map.get("cusIdL");
		cusNames = (List<String>) map.get("cusNames");
		//String codes = (String) map.get("codes");
		String cusIds = (String) map.get("cusIds");
		System.out.println("0000000000000000000000000000000-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		map = this.findTireArchivesWork(DataUtil.strToDate(workDtE), cusIds);
		//保存轮iD
		List<Integer> tireIds = (List<Integer>) map.get("tireIds");
		//里程 胎纹1 胎纹2 胎纹3 胎纹4
		List<List<Double>> tireValues = (List<List<Double>>) map.get("tireValues");
		//客户编码  品牌  规格 型号
		List<String> tireDetails = (List<String>) map.get("tireDetails");
		//轮胎对应客户的id
		List<Integer> tireCusIds = (List<Integer>) map.get("tireCusIds");
		List<Date> workDts = (List<Date>) map.get("workDts");
		System.out.println("11111111111111111111111111111111111111-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		map = this.findInspection(calendar.getTime(), DataUtil.strToDate(workDtE), cusIds, tireIds, tireValues, tireDetails, tireCusIds, workDts);
		tireIds = (List<Integer>) map.get("tireIds");
		//里程 胎纹1 胎纹2 胎纹3 胎纹4
		tireValues = (List<List<Double>>) map.get("tireValues");
		//客户编码  品牌  规格 型号
		tireDetails = (List<String>) map.get("tireDetails");
		//轮胎对应客户的id
		tireCusIds = (List<Integer>) map.get("tireCusIds");
		System.out.println("22222222222222222222222222222222222-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		map = this.findCustomerLimit(cusIds);
		List<String> limits = (List<String>) map.get("limits");
		List<List<Double>> limitValues = (List<List<Double>>) map.get("limitValues");
		System.out.println("333333333333333333333333333333333-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		for(int i=0; i<tireIds.size(); i++){
			List<Double> tireValue = tireValues.get(i);
			String tireDetail = tireDetails.get(i);
			int IDIndex = cusIdL.indexOf(tireCusIds.get(i));
			
			Weelly weel0 = wlList.get(0);
			Weelly weel = wlList.get(IDIndex);
			
			boolean falg = true;
			
			int detIndex = limits.indexOf(tireDetail+"剩余胎纹");
			if(detIndex >-1){
				List<Double> limitValue = limitValues.get(detIndex);
				Double tread = 0.0;
				Double j=0.0;
				if(tireValue.get(1) > 0.0){
					tread += tireValue.get(1)*100;
					j++;
				}
				if(tireValue.get(2) > 0.0){
					tread += tireValue.get(2)*100;
					j++;
				}
				if(tireValue.get(3) > 0.0){
					tread += tireValue.get(3)*100;
					j++;
				}
				if(tireValue.get(4) > 0.0){
					tread += tireValue.get(4)*100;
					j++;
				}
				if(j > 0 && tread>0){
					tread = tread/j;
				}
				if(tread!=0){
					if(tread < limitValue.get(2)*100){
						falg = false;
						weel0.setThisMonthPlan(weel0.getThisMonthPlan()+1);
						weel.setThisMonthPlan(weel.getThisMonthPlan()+1);
					}
					if(tread < limitValue.get(1)*100){
						weel0.setTreadLimiWarning(weel0.getTreadLimiWarning()+1);
						weel.setTreadLimiWarning(weel.getTreadLimiWarning()+1);
					}else if(tread < limitValue.get(0)*100){
						weel0.setTreadWarning(weel0.getTreadWarning()+1);
						weel.setTreadWarning(weel.getTreadWarning()+1);
					}
				}
			}
			detIndex = limits.indexOf(tireDetail+"使用里程");
			if(detIndex >-1){
				List<Double> limitValue = limitValues.get(detIndex);
				if(tireValue.get(0)!=0){
					if(tireValue.get(0) > limitValue.get(2)){
						if(falg){
							weel0.setThisMonthPlan(weel0.getThisMonthPlan()+1);
							weel.setThisMonthPlan(weel.getThisMonthPlan()+1);
						}
					}
					if(tireValue.get(0) >= limitValue.get(1)){
						weel0.setMileageLimitWarning(weel0.getMileageLimitWarning()+1);
						weel.setMileageLimitWarning(weel.getMileageLimitWarning()+1);
					}else if(tireValue.get(0) >= limitValue.get(0)){
						weel0.setMileageWarning(weel0.getMileageWarning()+1);
						weel.setMileageWarning(weel.getMileageWarning()+1);
					}
				}
			}
			wlList.set(0, weel0);
			wlList.set(IDIndex, weel);
		}
		System.out.println("44444444444444444444444444444444444-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		//本周更新
		//销售维修
		calendar.add(Calendar.MONTH, 2);
		for(int i=1; i<cusNames.size(); i++){
			String s = cusNames.get(i);
			Integer bzgx = erpSaleRepairSaleMapper.selectSizeByCustNameAndOutto("%客户%", s, workDtS, workDtE);
			Integer bygx = erpSaleRepairSaleMapper.selectSizeByCustNameAndOutto("%客户%", s,  sdf.format(calendar.getTime()), workDtE);
			Weelly weel0 = wlList.get(0);
			Weelly weel = wlList.get(i);
			weel0.setThisWeel(weel0.getThisWeel()+bzgx);
			weel.setThisWeel(weel.getThisWeel()+bzgx);
			weel0.setThisMonth(weel0.getThisMonth()+bygx);
			weel.setThisMonth(weel.getThisMonth()+bygx);
			wlList.set(0, weel0);
			wlList.set(i, weel);
		}
		System.out.println("5555555555555555555555555555555555-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		for(int i=1; i<cusNames.size(); i++){
			String s = cusNames.get(i);
			Integer bzgx = erpSaleRepairRepairMapper.selectBySourseAndOutTo("%客户%", "%客户%", s, workDtS, workDtE);
			Integer bygx = erpSaleRepairRepairMapper.selectBySourseAndOutTo("%客户%", "%客户%", s, sdf.format(calendar.getTime()), workDtE);
			Weelly weel0 = wlList.get(0);
			Weelly weel = wlList.get(i);
			weel0.setThisWeel(weel0.getThisWeel()+bzgx);
			weel.setThisWeel(weel.getThisWeel()+bzgx);
			weel0.setThisMonth(weel0.getThisMonth()+bygx);
			weel.setThisMonth(weel.getThisMonth()+bygx);
			wlList.set(0, weel0);
			wlList.set(i, weel);
		}
		System.out.println("66666666666666666666666666666666666-------"+(new Date().getTime()-startTIme));
		
		startTIme = new Date().getTime();
		for(int i=0; i<wlList.size(); i++){
			Weelly we = wlList.get(i);
			if(we.getThisMonth() ==0 || we.getThisMonthPlan() == 0){
				we.setUpdateCompleted(0);
			}else{
				we.setUpdateCompleted((we.getThisMonth()*100)/we.getThisMonthPlan());
			}
			we.setRecentUpdatePlan(we.getThisMonthPlan()-we.getThisMonth());
			wlList.set(i, we);
		}
		System.out.println("77777777777777777777777777777777777-------"+(new Date().getTime()-startTIme));
		return new Result<List<Weelly>>(wlList,wlList.size());
	}
	
	
	/**
	 * 获得所有客户和初始化返回值
	 * @param name
	 * @param cusCodes
	 * @param cusIdL
	 * @param cusNames
	 * @param wlList
	 * @return
	 */
	public Map<String,Object> findCustomer(Integer custId, List<Integer> cusCodes, List<Integer> cusIdL, List<String> cusNames, List<Weelly> wlList){
		Map<String,Object> map = new HashMap<String,Object>();
		
		//根据客户名称获取客户编码
		Integer cusCode = erpCustomerMapper.selectById(custId).getCusCode();
		
		//根据客户编码获取当前客户和当前客户的下级单位
		List<ErpCustomer> cuss = erpCustomerMapper.selectList(new EntityWrapper<ErpCustomer>().like("cus_service_com", cusCode.toString()).or().eq("cus_code", cusCode));
		String codes = "''";
		String cusIds = "-1";
		
		for(ErpCustomer c : cuss){
			codes += ",'"+c.getCusCode()+"'";
			cusIds += ","+c.getId();
			Weelly w = new Weelly();
			w.setCusName(c.getCusName());
			w.setMileageWarning(0);
			w.setTreadWarning(0);
			w.setMileageLimitWarning(0);
			w.setTreadLimiWarning(0);
			w.setThisWeel(0);
			w.setThisMonthPlan(0);
			w.setAccident(0);
			w.setThisMonth(0);
			w.setUpdateCompleted(0);
			w.setRecentUpdatePlan(0);
			wlList.add(w);
			cusCodes.add(c.getCusCode());
			cusIdL.add(c.getId());
			cusNames.add(c.getCusName());
		}
		map.put("cusCodes", cusCodes);
		map.put("cusIdL", cusIdL);
		map.put("cusNames", cusNames);
		map.put("wlList", wlList);
		map.put("codes", codes);
		map.put("cusIds", cusIds);
		return map;
	}
	
	/**
	 * 查询轮胎里程
	 * @param workDtE
	 * @param cusIds
	 * @param tireIds
	 * @param tireValues
	 * @param mileageS
	 * @return
	 */
	public Map<String,Object> findTireArchivesWork(Date workDtE, String cusIds){
		Map<String,Object> map = new HashMap<String,Object>();
		
		Date DYdate = null;
		try {
			DYdate = sdf.parse("1970-01-01");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		TestPost tp = new TestPost();
		
		//保存轮iD
		List<Integer> tireIds = new ArrayList<Integer>();
		//里程 胎纹1 胎纹2 胎纹3 胎纹4
		List<List<Double>> tireValues = new ArrayList<List<Double>>();
		//客户编码  品牌  规格 型号
		List<String> tireDetails = new ArrayList<String>();
		//轮胎对应客户的id
		List<Integer> tireCusIds = new ArrayList<Integer>();
		//轮胎对应的 工作时间
		List<Date> workDts = new ArrayList<Date>();
		List<ErpMateriel> maters = erpMaterielMapper.selectWorkTime(cusIds);
		String Data = "";
		for(ErpMateriel mater:maters){
			Double gpsMileage = 0.00;
			if(mater.getMaterielLoad() == 1){
				ErpCustomerCar car = erpCustomerCarMapper.selectByTireId(mater.getId());
				if(car != null){
					try {
						Data = tp.testPost(car.getCarPlate());
					} catch (IOException e) {
						e.printStackTrace();
					}
					Data = Data.substring(1, Data.length() - 1);
				}
				if(Data==null){
					JSONObject jsStr = JSONObject.fromObject(Data);
					gpsMileage = jsStr.getDouble(("StarkMileage")) / 1000;
				}
			}
			tireIds.add(mater.getId());
			workDts.add(DYdate);
			ErpCustomerWarehouse customerWarehouse =erpCustomerWarehouseMapper.selectById(mater.getWarehouseId());
			int customerId = customerWarehouse.getCustomerId();
			
			tireDetails.add(customerId+mater.getMaterielBrand()+mater.getMaterielSpecifications()+mater.getMaterielModel());
			tireCusIds.add(customerId);
			
			List<Double> tireValue = new ArrayList<Double>();
			tireValue.add(0.0);
			tireValue.add(0.0);
			tireValue.add(0.0);
			tireValue.add(0.0);
			tireValue.add(0.0);
			
			
			//查询所有车辆轮胎信息
			List<ErpTireArchivesWork> taws = erpTireArchivesWorkMapper.selectByWorkDate(mater.getId(), DataUtil.dateToStr(workDtE));
			Double mileage = 0.00;
			for(ErpTireArchivesWork taw:taws){
				if(taw.getCalculatingMileage() == 1){
					tireValue.set(0,tireValue.get(0)+taw.getWorkMileage()-mileage);
				}
				mileage = taw.getWorkMileage();
			}
			if(gpsMileage > mileage){
				tireValue.set(0,tireValue.get(0)+gpsMileage-mileage);
			}
			tireValues.add(tireValue);
		}
		map.put("tireIds", tireIds);
		map.put("tireValues", tireValues);
		map.put("tireDetails", tireDetails);
		map.put("tireCusIds", tireCusIds);
		map.put("workDts", workDts);
		
		return map;
	}
	
	/**
	 * 查询物料寿命
	 * @param cusIds
	 * @return
	 */
	public Map<String,Object> findCustomerLimit(String cusIds){
		Map<String,Object> map = new HashMap<String,Object>();
		List<ErpCustomerLimit> cls = erpCustomerLimitMapper.selectByCustIds(cusIds);
		
		List<String> limits = new ArrayList<String>();
		List<List<Double>> limitValues = new ArrayList<List<Double>>();
		for(ErpCustomerLimit cl:cls){
			String limit = cl.getCustomerId()+cl.getLimBrand()+cl.getLimSf()+cl.getLimModel()+cl.getLimType();
			if(limits.indexOf(limit) == -1){
				limits.add(limit);
				List<Double> limitValue = new ArrayList<Double>();
				limitValue.add(Double.valueOf(cl.getLimPrompt()));
				limitValue.add(Double.valueOf(cl.getLimLimited()));
				limitValue.add(Double.valueOf(cl.getLimReplacement()));
				limitValues.add(limitValue);
			}
		}
		map.put("limits", limits);
		map.put("limitValues", limitValues);
		return map;
	}
	
	/**
	 * 获取周胎纹
	 * @param workDtS
	 * @param workDtE
	 * @param cusIds
	 * @return
	 */
	public Map<String,Object> findInspection(Date workDtS, Date workDtE, String cusIds, List<Integer> tireIds,
			List<List<Double>> tireValues, List<String> tireDetails, List<Integer> tireCusIds, List<Date> workDts){
		Map<String,Object> map = new HashMap<String,Object>(); 
		List<Integer>  cusWareIds =erpCustomerWarehouseMapper.selectBycusIds(cusIds);
		String wareId = "-1";
		for(Integer s: cusWareIds){
			wareId +=","+s;
		}
		List<Map<String, Object>> ihms = erpInspectionContentMapper.selectByWareIds(DataUtil.dateToStr(workDtS),DataUtil.dateToStr(workDtE), wareId);
		List<Integer> tids = new ArrayList<Integer>();
		
		for(int i=0; i<ihms.size(); i++){
			int mid=Integer.parseInt(ihms.get(i).get("mId").toString());
			if(tids.indexOf(mid) == -1){
				tids.add(mid);
				int idIndex = tireIds.indexOf(mid);
				if( idIndex > -1 ){
					String inspectionDt=ihms.get(i).get("inspectionDt").toString();
					Date d = workDts.get(idIndex);
					Date dt=DataUtil.strToDate(inspectionDt);
					if(d.getTime() < dt.getTime()){
						String contentDt=ihms.get(i).get("dt").toString();
						Date dt1=DataUtil.strToDate(contentDt);
						workDts.set(idIndex, dt1);
						List<Double> tireValue = tireValues.get(idIndex);
						Double deepLines1 =0.0;
						Double deepLines2 =0.0;
						Double deepLines3 =0.0;
						Double deepLines4 =0.0;
						if (null==ihms.get(i).get("deepLines1")){
						 	deepLines1=0.0;
						}else{
							 deepLines1=Double.parseDouble(ihms.get(i).get("deepLines1").toString());
						}
				if (null==ihms.get(i).get("deepLines2")){
						 	deepLines2=0.0;
						}else{
							 deepLines2=Double.parseDouble(ihms.get(i).get("deepLines2").toString());
						}
					if (null==ihms.get(i).get("deepLines3")){
						 	deepLines3=0.0;
						}else{
							 deepLines3=Double.parseDouble(ihms.get(i).get("deepLines3").toString());
						}
if (null==ihms.get(i).get("deepLines4")){
						 	deepLines4=0.0;
						}else{
							 deepLines4=Double.parseDouble(ihms.get(i).get("deepLines1").toString());
						}



						tireValue.set(1, deepLines1);
						tireValue.set(2, deepLines2);
						tireValue.set(3, deepLines3);
						tireValue.set(4, deepLines4);
						tireValues.set(idIndex, tireValue);
					}
				}
			}
		}
		
		map.put("tireIds", tireIds);
		map.put("tireValues", tireValues);
		map.put("tireDetails", tireDetails);
		map.put("tireCusIds", tireCusIds);
		return map;
	}
}
